/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mwt.xml.xdbforms.xformlayer.impl;

import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.transform.Transformer;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import mwt.xml.xdbforms.xformlayer.XFormTransformer;
import mwt.xml.xdbforms.xformlayer.exception.XFormTransformerException;

/**
 * Progetto Master Web Technology
 * @author Gianfranco Murador, Cristian Castiglia, Matteo Ferri
 * @copyright (C) 2009, MCG08
 */
public class XFormsTransformerImpl implements XFormTransformer {


    private Map<String,String> parameters;
    private ErrorListener errorListener;
    private OutputStream outputStream;

    public XFormsTransformerImpl() {


    }

    public XFormsTransformerImpl(Map<String, String> parameters,
                                 ErrorListener errorListener,
                                 OutputStream outputStream) {
        this.parameters = parameters;
        this.errorListener = errorListener;
        this.outputStream = outputStream;
    }



    public void transform(StreamSource XSLTStream, DOMSource XMLSource) throws XFormTransformerException {

        

        TransformerFactory tf  = TransformerFactory.newInstance();
        tf.setErrorListener(errorListener);

        
        try {
            Transformer t =  tf.newTransformer(XSLTStream);
            tf.setErrorListener(errorListener);

            if(!parameters.isEmpty()){

                Iterator<Entry<String,String>> it = parameters.entrySet().iterator();
                while(it.hasNext()){
                    Entry<String,String> entry = it.next();
                    t.setParameter(entry.getKey(), entry.getValue());
                }
            }

            t.transform(XMLSource, new StreamResult(outputStream));


        } catch (TransformerException ex) {
            throw new XFormTransformerException(ex);
        }

    }

    public void setParameters(Map<String, String> parameters) {

        this.parameters = parameters;
    }

    public void setErrorListener(ErrorListener el) {

        errorListener = el;
    }


}
